package controllers

import (
	"bufio"
	// "encoding/json"
	// "fmt"
	"io/ioutil"
	// "mime/multipart"
	// "bytes"
	"helper"
	"io"
	"net/http"
	"os"
	"strconv"
	"strings"

	"golanger.com/utils"
	"jk/jklog"
)

type PageIndex struct {
	Application
}

func init() {
	App.RegisterController("index/", PageIndex{})
}

func (p *PageIndex) Before_() []map[string]string {
	return []map[string]string{
		map[string]string{
			"_FILTER": "getIndex",
			"_ALL":    "allow",
			"Index":   "deny",
		},
		map[string]string{
			"_FILTER":  "GetTest",
			"TestPage": "allow",
		},
		map[string]string{
			"_FILTER":  "GetTest1",
			"TestPage": "allow",
			"Index":    "allow",
		},
	}
}

func (p *PageIndex) After_() []map[string]string {
	return []map[string]string{
		map[string]string{
			"_FILTER":  "after",
			"_ALL":     "allow",
			"TestPage": "deny",
		},
	}
}

func (p *PageIndex) After_Index(w http.ResponseWriter, r *http.Request) {
	//	fmt.Println("After_Index")
}

type FileEachName struct {
	Name string
}

func (p *PageIndex) Index(w http.ResponseWriter, r *http.Request) {

	p.Document.Title = p.LANG["index"]
	var allfiles []FileEachName
	var downloadfiles []FileEachName
	fi, err := ioutil.ReadDir(helper.GetCmdLineDir())
	if err == nil {
		allfiles = []FileEachName{}
		for _, fi := range fi {
			if !fi.IsDir() && "." != string((fi.Name())[0]) {
				file := FileEachName{}
				file.Name = string(fi.Name())
				allfiles = append(allfiles, file)
			}
		}

		/* get download file name */

		fi, _ = ioutil.ReadDir(helper.GetAppDir())
		downloadfiles = []FileEachName{}
		for _, fi := range fi {
			if "." != string((fi.Name())[0]) {
				file := FileEachName{}
				file.Name = string(fi.Name())
				downloadfiles = append(downloadfiles, file)
			}
		}
	}

	body := utils.M{}
	body["allfiles"] = allfiles
	body["downloadfiles"] = downloadfiles
	p.Body = body
	return
}

func (p *PageIndex) Interface(w http.ResponseWriter, r *http.Request) {
}

func (p *PageIndex) Nfs(rw http.ResponseWriter, req *http.Request) {
	p.Document.Title = "install nfs and tftp"
}

func (p *PageIndex) Product(rw http.ResponseWriter, req *http.Request) {
	p.Document.Title = "Introduce Product"
}

func (p *PageIndex) Uploadfile(rw http.ResponseWriter, req *http.Request) {
	// _ := req.Header.Get("Content-Length")

	file, handle, err := req.FormFile("upfile")

	if err == nil {
		uploadingtitle := "Uploading file [" + handle.Filename + "] Now"
		jklog.L().Infoln("uploadingtitle: ", uploadingtitle)

		p.Document.Title = uploadingtitle

		f, err := os.OpenFile(helper.GetAppDir()+"/"+handle.Filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
		if err != nil {
			jklog.L().Errorln(err)
		}

		io.Copy(f, file)
		defer f.Close()
		defer req.Body.Close()
		rw.WriteHeader(200)
	} else {
		rw.WriteHeader(http.StatusNotFound)
	}
}

func (p *PageIndex) DealCmd(w http.ResponseWriter, r *http.Request) {
	filename := p.GET["name"]
	p.Document.Title = filename
	path := helper.GetCmdLineDir() + "/" + filename
	file := JKReadFile(path)

	w.Write([]byte(file))
}

func (p *PageIndex) DownloadFiles(w http.ResponseWriter, r *http.Request) {
	filename := p.GET["title"]
	path := helper.GetAppDir() + "/" + filename

	/* read file to bytes */
	file, err := os.Open(path)
	if err != nil {
		w.Write([]byte(path + " not exist"))
		return
	}
	defer file.Close()

	/* get file status with size */
	fileinfo, err := file.Stat()
	if err != nil {
		w.Write([]byte(path + " not exist"))
		return
	}
	filesize := fileinfo.Size()
	sizestr := strconv.FormatInt(filesize, 10)

	w.Header().Set("Content-Length", sizestr)
	w.Header().Set("Content-Type", "application/octet-stream")
	w.Header().Set("Accept-Ranges", "bytes")
	// w.Header().Set("Connection", "keepalive")
	// w.Header().Set("Content-Disposition", "attachment")

	w.WriteHeader(http.StatusOK)
	io.CopyN(w, file, filesize)
}

func JKReadFile(filename string) string {
	b, err := ioutil.ReadFile(filename)
	if err != nil {
		jklog.L().Errorln(err)
	}
	var filestr string
	var line []byte
	rd := bufio.NewReader(strings.NewReader(string(b)))
	for err == nil {
		isP := true
		for isP {
			line, isP, err = rd.ReadLine()
			if err != nil && err.Error() != "EOF" {
			}
			filestr += string(line)
			filestr += string("\n")
		}
	}
	return filestr
}

func (p *PageIndex) Filter_getIndex() {
	//	fmt.Println("GetIndex")
}

func (p *PageIndex) Filter_GetTest(r *http.Request) {
	//	fmt.Println("GetTest")
	//	fmt.Println(r.URL)
}

func (p *PageIndex) Filter_GetTest1() {
	//	fmt.Println("GetTest1")
}

func (p *PageIndex) Filter_after() {
	//	fmt.Println("Filter_after")
}

func (p *PageIndex) Start(w http.ResponseWriter, r *http.Request) {
}
